<template>
  <div class="map-picker">
    <em-cell
      :title="title"
      center
      is-link
      :value-class="['em-ellipsis',linkTitle && 'map-picker__is-linked']"
      @click="showDialog = true"
    >
      {{ linkTitle || '选择链接' }}
    </em-cell>
    <el-dialog
      title="选择链接"
      :visible.sync="showDialog"
      width="500"
      destroy-on-close
      append-to-body
      custom-class="middle-dialog"
      lock-scroll
    >
      <map-fence v-model="checkedLink" />
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="onClearLink">清 除</el-button>
        <el-button
          type="primary"
          @click="onCheckedLink"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import MapFence from '@/components/MapFence'
export default {
  name: 'WeblinkCell',
  components: {
    MapFence
  },
  props: {
    value: {
      type: Object,
      default: null
    },
    title: {
      type: String,
      default: '链接地址'
    }
  },
  provide() {
    return {
      usage: () => this.usage
    }
  },
  data() {
    return {
      usage: 'weblink',
      checkedLink: null,
      showDialog: false,
      saving: false,
      activeIndex: undefined
    }
  },
  computed: {
    link: {
      get() {
        return this.value
      },
      set(v) {
        this.value = v
      }
    },
    linkTitle() {
      if (this.link) {
        if (this.link.title) {
          return this.link.title
        }
        return this.link.map_data && this.link.map_data.title
      }
      return ''
    }
  },
  watch: {},
  created() {
    this.checkedLink = { ...this.link }
    console.log('created set checkedLink', this.checkedLink)
  },
  methods: {
    onCheckedLink() {
      if (this.checkedLink) {
        this.onEmitInput(this.checkedLink)
      } else {
        this.showDialog = false
      }
    },
    onClearLink() {
      this.onEmitInput({
        map_id: 0,
        fence_id: null,
        map_data: null
      })
    },
    onEmitInput(data) {
      this.$emit('input', data)
      this.showDialog = false
    }
  }
}
</script>

<style lang="scss">
.picker-button {
  cursor: pointer;
}
.middle-dialog {
  height: 70vh;
  display: flex;
  flex-direction: column;
  .el-dialog__footer,
  .el-dialog__header {
    padding: 20px;
  }
  .el-dialog__body {
    flex: 1;
    overflow: hidden;
    padding: 0;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
  }
}
.map-picker__is-linked {
  color: #ff6600;
}
</style>
